package com.qxl.forest.core.aop;

import com.qxl.forest.core.log.LogManager;
import com.qxl.forest.core.log.factory.LogTaskFactory;
import com.qxl.forest.core.shiro.ShiroKit;
import com.qxl.forest.exception.BizExceptionEnum;
import com.qxl.forest.exception.BussinessException;
import com.qxl.forest.exception.InvalidKaptchaException;
import com.qxl.forest.util.CommRes;
import com.qxl.forest.util.HttpKit;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.UnknownSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;

import static com.qxl.forest.util.HttpKit.getIp;

/**
 * @Author: qiuxinlin
 * @Dercription: 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 * @Date: 2017/12/19
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 拦截业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BussinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public CommRes notFount(BussinessException e) {
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
        log.error("业务异常:", e);
        return CommRes.errorRes(Integer.toString(e.getCode()), e.getMessage());
    }

    /**
     * 用户未登录
     *
     * @param e
     * @return
     */
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public CommRes unAuth(AuthenticationException e) {
        log.error("用户未登陆：", e);
        return CommRes.errorRes(Integer.toString(HttpStatus.UNAUTHORIZED.value()), "用户未登陆");
    }

    /**
     * 账号被冻结
     *
     * @param e
     * @return LockedAccountException
     */
    @ExceptionHandler(DisabledAccountException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public CommRes accountLocked(DisabledAccountException e) {
        String username = HttpKit.getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "账号被冻结", getIp()));
        return CommRes.errorRes(Integer.toString(HttpStatus.UNAUTHORIZED.value()), "账号被冻结");
    }

    /**
     * 账号密码错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(CredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public CommRes credentials(CredentialsException e) {
        String username = HttpKit.getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "账号密码错误", getIp()));
        return CommRes.errorRes(Integer.toString(HttpStatus.UNAUTHORIZED.value()), "账号密码错误");
    }

    /**
     * 验证码错误
     *
     * @param e
     * @return
     */
    @ExceptionHandler(InvalidKaptchaException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public CommRes credentials(InvalidKaptchaException e) {
        String username = HttpKit.getRequest().getParameter("username");
        LogManager.me().executeLog(LogTaskFactory.loginLog(username, "验证码错误", getIp()));
        return CommRes.errorRes(Integer.toString(HttpStatus.BAD_REQUEST.value()), "验证码错误");
    }

    /**
     * 无权访问该资源
     *
     * @param e
     * @return
     */
    @ExceptionHandler(UndeclaredThrowableException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public CommRes credentials(UndeclaredThrowableException e) {
        log.error("权限异常!", e);
        return CommRes.errorRes(Integer.toString(BizExceptionEnum.NO_PERMITION.getCode()), BizExceptionEnum.NO_PERMITION.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public CommRes notFount(RuntimeException e) {
        LogManager.me().executeLog(LogTaskFactory.exceptionLog(ShiroKit.getUser().getId(), e));
        log.error("运行时异常:", e);
        return CommRes.errorRes(Integer.toString(BizExceptionEnum.SERVER_ERROR.getCode()), BizExceptionEnum.SERVER_ERROR.getMessage());
    }

    /**
     * session失效的异常拦截
     *
     * @param e
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(InvalidSessionException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public CommRes sessionTimeout(InvalidSessionException e, HttpServletRequest request, HttpServletResponse response) {
        assertAjax(request, response);
        try {
            response.sendRedirect("http://localhost:8080/");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return CommRes.errorRes(Integer.toString(HttpStatus.BAD_REQUEST.value()), "session超时");
    }

    /**
     * session异常
     *
     * @param e
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler(UnknownSessionException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public CommRes sessionTimeout(UnknownSessionException e, HttpServletRequest request, HttpServletResponse response) {
        assertAjax(request, response);
        return CommRes.errorRes(Integer.toString(HttpStatus.BAD_REQUEST.value()), "session超时");
    }

    private void assertAjax(HttpServletRequest request, HttpServletResponse response) {
        if (request.getHeader("x-requested-with") != null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            //如果是ajax请求响应头会有，x-requested-with
            response.setHeader("sessionstatus", "timeout");//在响应头设置session状态
        }
    }

}
